from celery import Celery
from celery.schedules import crontab
from app.core.config import settings

# 创建Celery实例
celery_app = Celery(
    "shipment_monitor",
    broker=settings.REDIS_BROKER_URL,
    backend=settings.REDIS_BACKEND_URL,
    include=['app.tasks.shipment_tasks']
)

# 配置
celery_app.conf.update(
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    timezone='Asia/Shanghai',
    enable_utc=False,  # 禁用UTC，使用本地时区
    task_track_started=True,
    task_time_limit=30 * 60,  # 30分钟超时
    task_soft_time_limit=25 * 60,  # 25分钟软超时
    worker_prefetch_multiplier=1,
    worker_max_tasks_per_child=1000,
)

# 动态配置定时任务
celery_app.conf.beat_schedule = {
    'monitor-shipments': {
        'task': 'app.tasks.shipment_tasks.monitor_shipments_task',
        'schedule': crontab(minute='*/5'),  # 默认每5分钟执行一次，后续从数据库读取
    },
}